#include <func.h>
#include "Task.h"

void do_register(void* arg, Thread* thread)
{
    // 1. 解析参数
    Param* param = (Param*) arg;
    int epfd = param->epfd;
    int connfd = param->connfd;
    // 用户名 密码
    char* username = strtok(param->req.value, SPACES);
    char* passwd = strtok(NULL, SPACES);
    // printf("INFO: %s %s\n", username, passwd);

    // 2. 判断用户名是否已经被注册
    MYSQL* mysql = thread->mysql;

    Response resp;
    bzero(&resp, sizeof(resp));

    if (username_exist(mysql, username) > 0) {
        resp.status = RESP_EXIST;
        resp.length = 0;
    } else {
        username_register(mysql, username, passwd);
        resp.status = RESP_OK;
        resp.length = 0;
    }
    // 3. 发送响应
    int length = 2 * sizeof(int) + resp.length;
    send(connfd, &length, sizeof(int), MSG_WAITALL);
    send(connfd, &resp, length, MSG_WAITALL);
    // 4. 将connfd重新添加到epfd 
    epoll_add(epfd, connfd);
    free(arg);
}
